package com.linghang.wusthelpercompetition.service;


import com.linghang.wusthelpercompetition.utils.JwtUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
@Service
public class MyTokenService {
    private final RedisTemplate<String, Object> redisTemplate;
    private final JwtUtils jwtUtils;

    public MyTokenService(RedisTemplate<String, Object> redisTemplate, JwtUtils jwtUtils) {
        this.redisTemplate = redisTemplate;
        this.jwtUtils = jwtUtils;
    }

    // 生成Token并缓存用户信息，缓存过期时间1天
    public String createToken(String userId, Object userInfo) {
        String token = jwtUtils.generateToken(userId);
        redisTemplate.opsForValue().set("TOKEN:" + token, userInfo, 1, TimeUnit.DAYS);
        return token;
    }

    // 从Token中获取用户ID
    public String getUid(String token){
        return (String) redisTemplate.opsForValue().get("LingHangToken:"+token);
    }

    // 根据token从Redis获取用户信息
    public Object getUserFromToken(String token) {
        return redisTemplate.opsForValue().get("TOKEN:" + token);
    }

    // 删除Redis中保存的token，实现注销
    public void deleteToken(String token) {
        redisTemplate.delete("TOKEN:" + token);
    }
}
